package com.example.demo2.config;

import com.example.demo2.pojo.data.AdminDO;
import com.example.demo2.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRelam extends AuthorizingRealm {
    @Autowired
    AdminService adminService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        System.out.println("执行了=>doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //给所有登录的用户授权
        //info.addStringPermission("user:add");
        //拿到当前登录的用户对象
        Subject subject = SecurityUtils.getSubject();
        AdminDO currentUser = (AdminDO) subject.getPrincipal();
        //设置当前用户的权限(从数据库中获取的权限)
        info.addStringPermission(currentUser.getIdentity());
        return info;

    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>doGetAuthenticationInfo");
        UsernamePasswordToken userToken=(UsernamePasswordToken) token;
        //上数据库查询有没有这个用户
        AdminDO adminDO=adminService.findByName(userToken.getUsername());
        //User user = userService.queryUserByName(userToken.getUsername());
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",adminDO);
        if (adminDO==null){//没有这个人
            return null;
        }
        //第一个参数可以把user对象里的东西传到上面的授权方法里，第二个参数是密码，shiro自动帮我们进行判断
        return new SimpleAuthenticationInfo(adminDO,adminDO.getPassword(),"");

    }
}
